package com.digitalchina.lxnsy.activity.old;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.CityRecyclerAdapter;
import com.digitalchina.lxnsy.adapter.ResultListAdapter;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.base.BaseApplication;
import com.digitalchina.lxnsy.base.CitySelectManager;
import com.digitalchina.lxnsy.entity.CityList;
import com.digitalchina.lxnsy.entity.SelectedCityVO;
import com.digitalchina.lxnsy.service.LocationService;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.ViewHolder;
import com.digitalchina.lxnsy.widget.EdgeLabelView;

import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.LatelyCity;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/2/17 16:06
 * 修改备注：
 * ================================================
 */

public class AddressSelectActivity extends BaseActivity {
    public static final String KEY_PICKED_CITY = "picked_city";
    private EdgeLabelView edgeLabelView;
    private TextView tv;
    private RecyclerView recyclerView;
    private CityList cityList = new CityList();
    private CitySelectManager manager;
    private List<City> mHotCitys;
    //LBS
    private final int SDK_PERMISSION_REQUEST = 127;
    private final int LBS_SUCCESS = 128;
    private String permissionInfo;
    private LocationService locationService;
    private boolean isLocationSuccess = false;
    //ViewHolder
    private ViewHolder.SelectCountyViewHolder selectCountyHolder;
    private ViewHolder.LatelyCityViewHolder latelyCityHolder;
    private ViewHolder.CurrentCityViewHolder currentCityHolder;
    private ViewHolder.HotCityViewHolder hotCityHolder;
    private ViewHolder.CityListViewHolder cityListHolder;

    //searchview
    private ListView mResultListView;
    private ResultListAdapter mResultAdapter;
    private EditText searchBox;
    private ViewGroup emptyView;

    private List<County> countys = new ArrayList<>();//县区

    private String currentLocationCity = "正在定位..."; // 当前定位城市
    private String currentLocationDistrict = ""; // 当前定位城市所在区
    private String currentCity = ""; // 当前城市
    private SelectedCityVO mCityVO;

    private List<LatelyCity> latelyCities = new ArrayList<>(); // 最近访问

    private int locateCount = 0;

    @Override
    public void setLayout() {
        setTitle("地址选择");
        setContentLayout(R.layout.activity_address_select);
    }

    @Override
    public void initMember() {
        if (getIntent().hasExtra("selectCityVO")) {
            mCityVO = (SelectedCityVO) getIntent().getSerializableExtra("selectCityVO");
        }

        getPersimmions();
        initData();
        initSliderBar();
        initView();
    }

    /**
     * 侧边栏
     */
    private void initSliderBar() {
        edgeLabelView = (EdgeLabelView) findViewById(R.id.ed);
        tv = (TextView) findViewById(R.id.tv);
        edgeLabelView.setOnSlidingTouchListener(new EdgeLabelView.OnSlidingTouchListener() {
            @Override
            public void onSlidingTouch(String str) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                layoutManager.scrollToPositionWithOffset(getPositionByString(str), 0);
            }
        });
        edgeLabelView.setDialog(tv);
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SDK_PERMISSION_REQUEST) {

        }

    }

    private void initData() {
        manager = new CitySelectManager(cityList);
        manager.initCityData();
        latelyCities = manager.queryLatelyCity();
        mHotCitys = manager.initHotCities();
        mResultAdapter = new ResultListAdapter(this, null);
    }

    /**
     * 根据 右边导航的字母等，获取RecyclerView中的position
     */
    private int getPositionByString(String str) {
        int result;
        switch (str) {
            case "县区":
                result = 0;
                break;
            case "定位":
                result = 1;
                break;
            case "最近":
                result = 2;
                break;
            case "热门":
                result = 3;
                break;
            default:
                result = cityList.getPositionByLetter(str) + 4;
        }
        return result;
    }

    private void initView() {
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        searchBox = (EditText) findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    mResultListView.setVisibility(View.VISIBLE);
                    List<City> result = manager.searchCity(keyword);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                manager.saveLatelyCity(mResultAdapter.getItem(position).city_code, mResultAdapter.getItem(position).city_name);
                SelectedCityVO cityVO = new SelectedCityVO();
                cityVO.setCityCode(mResultAdapter.getItem(position).city_code);
                cityVO.setCityName(mResultAdapter.getItem(position).city_name);
                back(cityVO);
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//不动的状态
                    tv.setVisibility(View.GONE);
                } else {
                    tv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int position = ((LinearLayoutManager) recyclerView.getLayoutManager())
                        .findFirstVisibleItemPosition();
                switch (position) {
                    case 0:
                        if (!tv.getText().toString().equals("县区")) {
                            tv.setText("县区");
                        }
                        break;
                    case 1:
                        if (!tv.getText().toString().equals("定位")) {
                            tv.setText("定位");
                        }
                        break;
                    case 2:
                        if (!tv.getText().toString().equals("最近")) {
                            tv.setText("最近");
                        }
                        break;
                    case 3:
                        if (!tv.getText().toString().equals("热门")) {
                            tv.setText("热门");
                        }
                        break;
                    default:
                        //poisition > 3 的情况
                        String tmp = cityList.getList().get(position - 4).getPinyin().substring(0, 1);
                        if (!tv.getText().toString().equals(tmp)) {
                            tv.setText(tmp);
                        }
                }
            }
        });

        recyclerView.setAdapter(new CityRecyclerAdapter(this, cityList, mHotCitys) {
            @Override
            public void initHolderData(final RecyclerView.ViewHolder viewHolder) {

                if (viewHolder instanceof ViewHolder.SelectCountyViewHolder) {//选择区县
                    selectCountyHolder = (ViewHolder.SelectCountyViewHolder) viewHolder;
                    selectCountyHolder.setOnCountyClickListener(new ViewHolder.SelectCountyViewHolder.OnCountyClickListener() {
                        @Override
                        public void onCountyClick(County county) {
                            City city = manager.queryCityWithCode(county.city_code);
                            manager.saveLatelyCity(city.city_code, city.city_name);
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(city.city_code);
                            cityVO.setCityName(city.city_name);
                            cityVO.setCountyCode(county.county_code);
                            cityVO.setCountyName(county.county_name);
                            back(cityVO);
                        }

                        @Override
                        public void displayCounty() {
                            //执行加载过程，需要异步
                            new AsyncTask<Void, Void, List<County>>() {
                                @Override
                                protected List<County> doInBackground(Void... params) {
                                    try {
                                        Thread.sleep(800);
                                        City city;
                                        if (getIntent().hasExtra("selectCityVO") && mCityVO.getCityName() != null) {
                                            city = manager.queryCityWithCityName(mCityVO.getCityName());
                                        } else {
                                            city = manager.queryCityWithCityName(currentLocationCity);
                                        }
                                        if (null == city)
                                            return countys;
                                        countys = manager.queryCounties(city.city_code);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    return countys;
                                }

                                @Override
                                protected void onPostExecute(List<County> c) {
                                    selectCountyHolder.loadDataComplete(c);
                                    selectCountyHolder.clickAble();//设置可点击
                                    if (countys.size() == 0) {
                                        selectCountyHolder.showNoData();
                                    } else {
                                        selectCountyHolder.hideNoData();
                                    }
                                }
                            }.execute();
                        }
                    });
                } else if (viewHolder instanceof ViewHolder.LatelyCityViewHolder) {
                    latelyCityHolder = (ViewHolder.LatelyCityViewHolder) viewHolder;
                    latelyCityHolder.initData(latelyCities);
                    latelyCityHolder.setOnLatelyCityClickListener(new ViewHolder.LatelyCityViewHolder.OnLatelyCityListener() {
                        @Override
                        public void onLatelyCityOneClick(LatelyCity latelyCity) {
                            manager.saveLatelyCity(latelyCity.getCity_code(), latelyCity.getCity_name());
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(latelyCity.getCity_code());
                            cityVO.setCityName(latelyCity.getCity_name());
                            back(cityVO);
                        }

                        @Override
                        public void onLatelyCityTwoClick(LatelyCity latelyCity) {
                            manager.saveLatelyCity(latelyCity.getCity_code(), latelyCity.getCity_name());
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(latelyCity.getCity_code());
                            cityVO.setCityName(latelyCity.getCity_name());
                            back(cityVO);
                        }

                        @Override
                        public void onLatelyCityThreeClick(LatelyCity latelyCity) {
                            manager.saveLatelyCity(latelyCity.getCity_code(), latelyCity.getCity_name());
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(latelyCity.getCity_code());
                            cityVO.setCityName(latelyCity.getCity_name());
                            back(cityVO);
                        }
                    });
                } else if (viewHolder instanceof ViewHolder.CurrentCityViewHolder) {
                    currentCityHolder = (ViewHolder.CurrentCityViewHolder) viewHolder;
                    if (!StringUtil.isStrEmpty(mCityVO.getCityName())) {
                        selectCountyHolder.tvCurrentCity.setText(StringUtil.jointString(mCityVO.getCityName(), StringUtil.isStrEmpty(mCityVO.getCountyName()) ? "" : mCityVO.getCountyName()));
                    }
                    currentCityHolder.setOnCurrentCityClickListener(new ViewHolder.CurrentCityViewHolder.OnCurrentCityListener() {
                        @Override
                        public void onCurrentCityOneClick(City currentCity) {
                            if (isLocationSuccess) {
                                manager.saveLatelyCity(currentCity.city_code, currentCity.city_name);
                                SelectedCityVO cityVO = new SelectedCityVO();
                                cityVO.setCityCode(currentCity.city_code);
                                cityVO.setCityName(currentCity.city_name);
                                back(cityVO);
                            } else if (null == currentCity) {
                                currentCityHolder.tvCurrenCity.setText("正在定位...");
                                locationService.start();
                            }
                        }
                    });
                } else if (viewHolder instanceof ViewHolder.HotCityViewHolder) {//热门城市
                    hotCityHolder = (ViewHolder.HotCityViewHolder) viewHolder;
                    hotCityHolder.setOnItemClickListener(new ViewHolder.HotCityViewHolder.OnItemClickListener() {
                        @Override
                        public void onItemListener(City city) {
                            manager.saveLatelyCity(city.city_code, city.city_name);
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(city.city_code);
                            cityVO.setCityName(city.city_name);
                            back(cityVO);
                        }
                    });
                } else if (viewHolder instanceof ViewHolder.CityListViewHolder) {//城市列表
                    cityListHolder = (ViewHolder.CityListViewHolder) viewHolder;
                    cityListHolder.setOnCityClickListener(new ViewHolder.CityListViewHolder.OnCityClickListener() {
                        @Override
                        public void onCityClick(City city) {
                            manager.saveLatelyCity(city.city_code, city.city_name);
                            SelectedCityVO cityVO = new SelectedCityVO();
                            cityVO.setCityCode(city.city_code);
                            cityVO.setCityName(city.city_name);
                            back(cityVO);
                        }
                    });
                }
            }

        });
    }

    private void back(SelectedCityVO cityVO) {
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, cityVO);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case LBS_SUCCESS:
                        if (mCityVO != null && !StringUtil.isStrEmpty(mCityVO.getCityName())) {//跳转页面带过来的不是空数据
                            currentLocationCity = mCityVO.getCityName();
                            selectCountyHolder.tvCurrentCity.setText(StringUtil.jointString(currentLocationCity, mCityVO.getCountyName() != null ? mCityVO.getCountyName() : ""));
                        } else {
                            selectCountyHolder.tvCurrentCity.setText(StringUtil.jointString(currentLocationCity, currentLocationDistrict));
                        }
                        currentLocationCity = msg.obj.toString();
                        if (isLocationSuccess) {
                            currentCityHolder.initData(manager.queryCityWithCityName(msg.obj.toString()));
                        } else {
                            currentCityHolder.initData(null);
                        }
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // -----------location config ------------
        locationService = ((BaseApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            locateCount = locateCount + 1;
            if (locateCount >= 10) { // 定位超过10次 停止定位
                locationService.stop();
            }
            if (null != location) {

                if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    isLocationSuccess = true;
                    currentLocationCity = location.getCity();
                    currentLocationDistrict = location.getDistrict();
                    locationService.stop();
                } else {
                    isLocationSuccess = false;
                    currentLocationCity = "";
                    locationService.stop();
                }

                Message message = new Message();
                message.what = LBS_SUCCESS;
                message.obj = currentLocationCity;
                mHandler.sendMessage(message);

            }

        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };

}
